
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class ReadWriter {

    private PrintWriter file;
    private Scanner m;

    public void writeToFile(ArrayList<BankAccount> accounts) {
        try {

            file = new PrintWriter("bank.txt");
            for (int i = 0; i < accounts.size(); i++) {
                if (accounts.get(i) != null) {
                    file.println(accounts.get(i).getAmount() + ":" + accounts.get(i).getName() + ":" + accounts.get(i).getAccountNr());
                }
            }
            System.out.println("you file is created ");
        } catch (Exception e) {
            System.out.println("this is wrong here in the writeToFile");
        } finally {
            file.close();
        }
    }

    public  ArrayList<BankAccount> readFromFile() {
        ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
        try {
            m = new Scanner(new File("bank.txt"));
            while (m.hasNext()) {
                String data = m.next();
                String[] splits = data.split(":");
                int amount = Integer.parseInt(splits[0]);
                String name = splits[1];
                int accountNr = Integer.parseInt(splits[2]);
                BankAccount acc = new BankAccount(amount, accountNr, name);
                accounts.add(acc);
                System.out.println("Account Number:  " + accountNr + " Name:     " + name + "  Amount:    " + amount);
            }

        } catch (FileNotFoundException | NumberFormatException e) {
            System.out.println("Can not find file");

        }finally{
            m.close();
        } 
        return accounts;
    }
}
